package com.kexun.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

/**
 * @author 浣滆?? liuyang
 * @version 鍒涘缓鏃堕棿锛?2017骞?9鏈?8鏃? 涓婂崍11:27:07
 * @Description MD5鍔犲瘑绫?
 */
public class JavaMD5 {
    private static byte[] hexBase = {48, 49, 50, 51,
            52, 53, 54, 55,
            56, 57, 97, 98,
            99, 100, 101, 102};

    public static String encrypt(String s) {
        if (s == null) return "";
        try {
            byte[] buff = s.getBytes("utf-8");
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            messagedigest.update(buff);
            byte[] result = messagedigest.digest();
            return byte2Hex(result);
        } catch (Exception e) {
        }
        return "";
    }

    public static String fileHash(String fileName) {
        try {
            byte[] buff = new byte[4096];
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(fileName);
            int len = 0;
            while ((len = fis.read(buff)) > 0) {
                messagedigest.update(buff, 0, len);
            }
            fis.close();
            byte[] result = messagedigest.digest();
            return byte2Hex(result);
        } catch (IOException ei) {
            return "";
        } catch (Exception e) {
        }
        return "";
    }

    public static String byte2Hex(byte[] b) {
        if (b == null) return "";
        StringBuffer tmp = new StringBuffer();
        int len = b.length;
        for (int i = 0; i < len; i++) {
            tmp.append((char) hexBase[((b[i] & 0xF0) >> 4)]);
            tmp.append((char) hexBase[(b[i] & 0xF)]);
        }
        while (tmp.length() < 16) tmp.append("00");

        return tmp.toString();
    }

    public static void main(String[] args) {
        System.out.println(encrypt("湖南信富廉航国际平台#ty123456"));
        //System.out.println(encrypt("pvgavv2019-03-21").length());
    }
}
